package com.yuanian.timingwheel.model.task.executestragy;

import com.yuanian.timingwheel.context.ExecutionContext;
import com.yuanian.timingwheel.model.task.base.BaseTask;
import com.yuanian.timingwheel.model.task.base.TaskExecutionResult;
import com.yuanian.timingwheel.respository.po.TaskEntity;
import java.io.Serializable;

/**
 * 重试策略
 */
public class RetryExecutionStrategy implements ExecutionStrategy, Serializable {

    //重试次数
    protected int retryCount;
    //已经重试次数
    protected int curRetryCount;

    public RetryExecutionStrategy() {
        this.retryCount = 10;
        this.curRetryCount = 0;
    }

    @Override
    public void onSuccess(BaseTask task, Object result) {
        task.getTaskInfo().postExecute(task, result);
    }

    @Override
    public void onFailure(BaseTask task, Exception e) {
        task.setTaskExecutionResult(new TaskExecutionResult(false, e.getMessage()));
        //重复执行
        if (curRetryCount++ < retryCount) {
            ExecutionContext.getInstance().getDayTimingWheel().loadTask(task);
        } else {
            TaskEntity.update(task);
        }
    }

}
